package com.xiaotu.spider.sohu.pageprocessor;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.TVProcessDataModel;
import com.xiaotu.common.util.*;
import com.xiaotu.spider.APageProcessor;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 搜狐视频 电视剧，网剧，网大 播放量
 */
@Component("SoHuPlayCountPageProcessor")
public class SoHuPlayCountPageProcessor extends APageProcessor {

    @Override
    protected Request getStartRequest(JSONObject target) {
        return new Request("http://so.tv.sohu.com/mts?box=1&wd="
                + KeywordEncode.encode(target.getString("tvName")));
    }

    @Override
    public void process(Page page) {
        Map<String, Object> tvMap = page.getRequest().getExtras();
        switch (this.getPageDataType(page)) {
            case Constants.PageDataType.SEARCH_LIST:
                this.searchListProcess(page, tvMap);
                break;
            case Constants.PageDataType.TV_RECORD:
                this.tvRecordProcess(page, tvMap);
                break;
            default:
                break;
        }
    }

    private void searchListProcess(Page page, final Map<String, Object> tvMap) {
        Html html = page.getHtml();
        final List<String> divList = html.xpath("//div[@class='ssItem cfix']")
                .all();

        String firstTime = html
                .xpath("//div[@class='ssItem cfix']/div[@class='center']"
                        + "/div[1]/span[@class='ndai']/text()").toString();
        firstTime = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, firstTime);
        tvMap.put("firstTime", firstTime);

        // 链接标签
        final List<String> aList = html
                .xpath("//div[@class='ssItem cfix']/div[@class='center']/div[1]/div[@class='infoA cfix lan_infoA']/h2/a")
                .all();
        if (aList.size() == 0)
            aList.addAll(html
                    .xpath("//div[@class='ssItem cfix']/div[@class='center']/div[@class='infoA cfix lan_infoA']/h2/a")
                    .all());

        if (null == aList || aList.size() == 0)
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);

        // 剧名称
        List<String> tvNames = html
                .xpath("//div[@class='ssItem cfix']/div[@class='center']/div[1]/div[@class='infoA cfix lan_infoA']/h2/a/font/text()")
                .all();
        if (tvNames.size() == 0)
            tvNames = html
                    .xpath("//div[@class='ssItem cfix']/div[@class='center']/div[@class='infoA cfix lan_infoA']/h2/a/font/text()")
                    .all();

        // 电视剧类型
        List<String> tvTypes = html
                .xpath("//div[@class='ssItem']/div[@class='center']/div[1]/div[@class='infoA cfix lan_infoA']/span[@class='label-red']/em/text()")
                .all();
        if (tvTypes.size() == 0)
            tvTypes = html
                    .xpath("//div[@class='ssItem']/div[@class='center']/div[@class='infoA cfix lan_infoA']/span[@class='label-red']/em/text()")
                    .all();

        List<String> actorsAndDirectorsUL = html
                .xpath("//div[@class='ssItem']/div[@class='center']/ul[@class='infoB cfix']")
                .all();

        List<List<String>> actorsAndDirectorsList = new ArrayList<List<String>>();

        for (int i = 0; i < actorsAndDirectorsUL.size(); i++) {
            Html actorsAndDirectorsHTML = new Html(actorsAndDirectorsUL.get(i));
            actorsAndDirectorsList
                    .add(actorsAndDirectorsHTML.xpath("//a/text()").all());
        }

        if (aList.size() != tvTypes.size()
                || aList.size() != actorsAndDirectorsList.size()
                || aList.size() != divList.size())
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);

        TVProcessUtils.addTVFromSearchList(page, tvMap, tvNames, aList, tvTypes,
                actorsAndDirectorsList, actorsAndDirectorsList,
                new TVProcessUtils.TVMatcher() {
                    @Override
                    protected boolean addTV(Page page,
                                            Map<String, Object> tvinfoMap, String name,
                                            String tvType, List<String> actors,
                                            List<String> directors, String link, int idx) {
                        if (TVProcessUtils.tvMatched(tvinfoMap, name,
                                TVProcessUtils.getTVType(tvType), actors,
                                directors) && Constants.SiteName.SOHU
                                .equals(new Html(divList.get(idx))
                                        .xpath("//div[@class='center']/div[@class='lan_resource']//ul/li[@class='on']/em/text()")
                                        .get() + "视频")
                        ) {
                            Html aHtml = new Html(link);
                            String playId = aHtml.xpath("//a/@_s_a").get();
                            if (StringUtils.isEmpty(playId)) throw new SpiderException(
                                    SpiderExceptionCode.DataInvalideException);
                            PageUtils.addTargetRequest(page,
                                    "http://count.vrs.sohu.com/count/query_Album.action?albumId="
                                            + playId,
                                    tvinfoMap, true);// 播放量链接
                            return true;
                        }
                        return false;
                    }
                }, null);
    }

    private void tvRecordProcess(Page page, Map<String, Object> tvMap) {
        String json = page.getRawText();
        if (StringUtils.isEmpty(json))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        json = RegexUtils.regexSearch("count=" + RegexUtils.REGEX_INTEGER,
                json);
        if (StringUtils.isEmpty(json))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        json = json.replace("count=", "").replace(".0", "");
        if (StringUtils.isEmpty(json))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        page.putField(TVProcessDataModel.class.getName(),
                new TVProcessDataModel(tvMap.get("tvid") + "", tvMap.get("tvName") + "",
                        Constants.SiteName.SOHU, json, null, null));
    }

    @Override
    protected String getSpiderType() {
        return Constants.SpiderTaskType.TV_SOHU;
    }

    @Override
    public String getPageDataType(Page page) {
        String url = page.getUrl().toString();
        if (url.contains("http://so.tv.sohu.com/mts?box=1&wd="))
            return Constants.PageDataType.SEARCH_LIST;
        else if (url
                .contains("http://count.vrs.sohu.com/count/query_Album.action"))
            return Constants.PageDataType.TV_RECORD;
        else
            return null;
    }

}
